﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ETL.Business.Handlers.ProjectActualResourceHandler;
using ETL.Business.Handlers.ProjectHandlers;
using ETL.Business.Handlers.ProjectTaskHandler;
using ETL.Business.Handlers.ProjectUserHandler;
using ETL.Business.Helpers;
using ETL.Business.Models;
using ETL.Common;
using ETL.Common.Logging;
using ETL.Web.CustomCredential;
using ETL.Web.Filters;
using ETL.Web.Models;
using WebMatrix.WebData;


namespace ETL.Web.Controllers
{
    public class ManageActualResourceController : Controller
    {
        //
        // GET: /ManageActualResource/

        [Authorize]
        [InitializeSimpleMembership]
        public ActionResult Index()
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return RedirectToAction("Login", "Account");

            // Program Initialize
            (new ProgramInitialize()).Execute(ETLCredential.UserId, ETLCredential.UserFullName);

            // prepare date of viewmodel
            var dashboardViewModel = new DashboardViewModel();

            #region Check user role for projects loading

            // Check roles of user
            if (!Roles.IsUserInRole(Constants.RoleName.Admin))
            {
                // Get all projects of this user, including selected project if it's existing
                List<ProjectModel> allProjectsOfThisUser = (new GetProjects()).Execute(ETLCredential.UserId).ToList();

                // Bind to viewmodel
                dashboardViewModel.ProjectModels = allProjectsOfThisUser;
                ViewBag.IsAdminRole = false;
                if (Roles.IsUserInRole(Constants.RoleName.Lead))
                {
                    ViewBag.IsLeadRole = true;
                }
                else
                {
                    ViewBag.IsLeadRole = false;
                }
            }
            else
            {
                // Get all projects of this user, including selected project if it's existing
                IEnumerable<ProjectModel> allProjectsOfThisUser = (new GetProjects()).Execute();

                // Bind to viewmodel
                dashboardViewModel.ProjectModels = allProjectsOfThisUser.ToList();
                ViewBag.IsAdminRole = true;
                ViewBag.IsLeadRole = false;
            }

            #endregion

            #region Check user role for other engineer dropdownlist

            // Admin roles only
            if (Roles.IsUserInRole(ETLCredential.UserId, Constants.RoleName.Admin))
            {
                dashboardViewModel.ProjectUserModels = (new GetAllUsers()).Execute();
                ViewBag.IsAdminRole = true;
            }

            #endregion

            // Get alert interval if user not log on to a task
            string alertInterval = ConfigurationManager.AppSettings["AlertInterval"];
            ViewBag.AlertInterval = alertInterval;


            return View(dashboardViewModel);
        }

        #region Logon to task

        /// <summary>
        /// Activity of logon to a specific task, with task id
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public string LogOnToATask(decimal taskId)
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return string.Empty;

            ProjectTaskModel currentTask = (new GetProjectTask()).Execute(taskId);

            decimal projectId = currentTask.ProjectId;

            // log on to task
            string result = (new LogOnToTask()).Execute(projectId, taskId, ETLCredential.UserId,
                                                        ETLCredential.UserFullName);

            return result;
        }

        /// <summary>
        /// Logon to last task
        /// </summary>
        /// <returns></returns>
        public string LogOnToLastTask()
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return string.Empty;

            ProjectActualResourceUsageModel lastActualResourceUsages =
                (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));

            if (lastActualResourceUsages.ActualResourceUsage != null)
            {
                decimal? tmpTask = lastActualResourceUsages.ActualResourceUsage.GEN_TASK_ID;
                decimal taskId = tmpTask == null ? 0 : tmpTask.Value;
                decimal? tmpPrj = lastActualResourceUsages.ActualResourceUsage.TASK.GEN_PROJECT_ID;
                decimal projectId = tmpPrj == null ? 0 : tmpPrj.Value;

                // log on to task
                string result = (new LogOnToTask()).Execute(projectId, taskId, ETLCredential.UserId,
                                                            ETLCredential.UserFullName);

                return result;
            }
            else
            {
                return null;
            }
        }

        #endregion

        #region Get tasks, project detailed by project

        /// <summary>
        /// Return a partial view of task grid
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult GetTask(decimal projectId)
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;


            if (projectId > 0)
            {
                IEnumerable<ProjectTaskModel> taskList = null;
                if(Roles.IsUserInRole(Constants.RoleName.Lead))
                {
                    taskList  = (new GetProjectTasks()).Execute(projectId);
                    //taskList = (new GetProjectTasks()).Execute(projectId, ETLCredential.UserId);
                }

                if (Roles.IsUserInRole(Constants.RoleName.Admin))
                {
                    taskList = (new GetProjectTasks()).Execute(projectId);
                }

                return PartialView("_TaskGridPartial", taskList);

            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// function to get project detailed content
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public string GetProjectDetail(int projectId)
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return string.Empty;

            ProjectModel currentProject = (new GetProject()).Execute(projectId);

            string result = string.Empty;
            if (currentProject != null)
            {
                result += currentProject.ProjectLeadEngineer + "#";
                result += String.Format("{0:MMM/dd/yyyy}", currentProject.ProjectStartDate) + "#";
                result += String.Format("{0:MMM/M/yyyy}", currentProject.ProjectEndDate) + "#";
                result += currentProject.ProjectStatus + "#";
            }
            return result;
        }

        /// <summary>
        /// Return a partial view of task grid
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public ActionResult GetActualResourceOfTask(decimal taskId)
        {
            try
            {
                // check authenticated status
                if (!WebSecurity.IsAuthenticated) return null;

                // convert to short
                ProjectTaskModel currentTask = (new GetProjectTask()).Execute(taskId);

                decimal projectId = currentTask.ProjectId;

                IEnumerable<ProjectActualResourceUsageModel> result = (new GetActualResourceUsage()).Execute(projectId,
                                                                                                             taskId);

                if (result != null)
                {
                    return PartialView("_ActualResourcePartial",
                                       result.OrderByDescending(s => s.GenActualResourceUsageId));
                }
                else
                {
                    return PartialView("_ActualResourcePartial", null);
                }
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                throw;
            }
        }

        #endregion

        #region ETL Actual Resource Usages

        public string CheckLastActualResourceUsage()
        {
            ProjectActualResourceUsageModel lastActualResourceUsages =
                (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));
            string message = "none";
            if (lastActualResourceUsages.ActualResourceUsage != null)
            {
                if (string.IsNullOrEmpty(lastActualResourceUsages.ClockOffBy))
                {
                    if (lastActualResourceUsages.EndDate == null)
                    {
                        message = "WalkedOff";
                    }
                    else
                    {
                        message = "SwipedOut";
                    }
                }
            }
            else if (lastActualResourceUsages.ActualResourceUsage == null)
            {
                message = "none";
            }

            return message;
        }

        public string UpdateActualResourceUsage(string genActualResourceUsageId, string startDate, string endDate)
        {
            decimal tmpId = 0;
            decimal.TryParse(genActualResourceUsageId, out tmpId);

            ProjectActualResourceUsageModel lastActualResourceUsages = (new GetActualResourceUsage()).Execute(tmpId);

            string taskId = lastActualResourceUsages.ActualResourceUsage.GEN_TASK_ID.ToString();
            decimal lastGenId = lastActualResourceUsages.GenActualResourceUsageId;
            string projectId = lastActualResourceUsages.ActualResourceUsage.TASK.GEN_PROJECT_ID.ToString();

            DateTime newEndTime = DateTime.Now;
            DateTime newEndTimeUkFormat = DateTime.Parse(endDate, CultureInfo.GetCultureInfo("en-us"));
            DateTime newStartTime = DateTime.Now;
            DateTime newStartTimeUkFormat = DateTime.Parse(startDate, CultureInfo.GetCultureInfo("en-us"));

            //bool b = DateTime.TryParse(dateTime, out newEndTime);
            bool b = DateTime.TryParse(newEndTimeUkFormat.ToString(), out newEndTime);
            bool c = DateTime.TryParse(newStartTimeUkFormat.ToString(), out newStartTime);

            if (b == false || c == false)
            {
                return "-1";
            }
            else
            {
                (new UpdateActualResourceUsage()).Execute(lastGenId, newStartTime, newEndTime);
                return "1";
            }
        }

        public ActionResult GetEditActualResourceDialog(string genActualResourceUsageId)
        {
            try
            {
                decimal tmpId = 0;
                decimal.TryParse(genActualResourceUsageId, out tmpId);

                ProjectActualResourceUsageModel curActualResourceUsage = (new GetActualResourceUsage()).Execute(tmpId);
                return PartialView("_EnterDatePartial", curActualResourceUsage);
            }
            catch (Exception ex)
            {
                // Logging
                LogService.Service.Error(ex.Message);
                // Redirect to 500 page
                throw new HttpException(404, "Page not found");
            }
        }

        #endregion
    }
}